<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>index page</title>
    <%@include file="common.jsp" %>
    <style type="text/css">
        .cale-body tr td {
            vertical-align: top;
            height: 130px;
        }

        .cale-body tr td .day-num {
            border-top: 5px solid transparent;
            font-size: 20px;
            color: #767676;
            padding-left:10px;
        }

        .onWay {
            background-color: #5e87b0 !important;
        }

        .overtime {
            background-color: #d9534f !important;
            color: #ffffff !important;
        }

        .end {
            background-color: #a8bc7b !important;
            color: #ffffff !important;
        }

        .calc {
            border: 1px solid #dddddd;
            table-layout: fixed;
        }

        .calc thead th {
            text-align: center;
        }

        .task {
            border-radius: 3px;
            word-wrap: break-word;
            width: 98%;
            margin-left: auto;
            margin-right: auto;
            margin-bottom:5px;
            position:absolute;
            padding-left:10px;
        }
        .packing{
            position: relative;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-default" role="navigation" id="topNav">
    <div class="container-fluid">
        <h1>Hello, Deam team.</h1>
    </div>
</nav>
<div class="container" id="content">
    <div class="row">
        <div class="form-horizontal">
            <div class="form-group">
                <div class="col-sm-4">
                    <select class="form-control" id="selectUser">
                        <c:forEach items="${users}" var="user">
                            <c:if test="${user.userid!='admin'}">
                                <option value="${user.id}">${user.username}</option>
                                <%--<option value="4">金鑫</option>--%>
                            </c:if>
                        </c:forEach>
                    </select>
                </div>
                <div class="col-sm-4"></div>
                <div class="col-sm-4">
                    <div class="col-sm-4 text-center" id="lastMonth"><span class="glyphicon glyphicon-chevron-left"
                                                                           aria-hidden="true"></span></div>
                    <div class="col-sm-4 text-center" id="currMonth"></div>
                    <div class="col-sm-4 text-center" id="nextMonth"><span class="glyphicon glyphicon-chevron-right"
                                                                           aria-hidden="true"></span></div>
                </div>
            </div>
        </div>
    </div>
    <br/>
    <div class="row">
        <div class="col-md-12">
            <div class="packing">
                <table width="100%" border="1" class="calc">
                    <thead id="cale-title" class="cale-title">
                    <tr>
                        <th>一</th>
                        <th>二</th>
                        <th>三</th>
                        <th>四</th>
                        <th>五</th>
                        <th>六</th>
                        <th>日</th>
                    </tr>
                    </thead>
                    <tbody id="cale-body" class="cale-body">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    //当前事件
    var date = new Date();

    $(function () {
//        window.resize = function(){
//            var userid = $("#selectUser").val();
//            deletePage();
//            var curr = Number($("#currMonth").text().substring(0, 1)) - 1;
//            init(date.getFullYear(), curr, null, userid);
//        }

        //init
        init(date.getFullYear(), date.getMonth(), date.getDate(), $("#selectUser").val());

        //onchange
        $("#selectUser").change(function () {
            var userid = $(this).val();
            deletePage();
            init(date.getFullYear(), date.getMonth(), date.getDate(), userid);
        });

        $("#lastMonth").click(function () {
            var userid = $("#selectUser").val();
            deletePage();
            var last = Number($("#currMonth").text().substring(0, 1)) - 1 - 1;
            init(date.getFullYear(), last, null, userid);
        });

        $("#nextMonth").click(function () {
            var userid = $("#selectUser").val();
            deletePage();
            var next = Number($("#currMonth").text().substring(0, 1));
            init(date.getFullYear(), next, null, userid);
        });
    });


    function init(year, month, day, userid) {
        $("#currMonth").text(month + 1 + "月份");

        //每月天数数组
        var m_days = new Array(31, 28 + is_leap(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
        //当月天数
        var currMonthDay = m_days[month];

        $(function () {
            //当月1号
            var firstDayDate = new Date(year, month, 1);
            //1号周几
            var firstDay = firstDayDate.getDay();
            //当月是多少行
            var rows = Math.ceil((currMonthDay + firstDay) / 7);

            for (i = 0; i < rows; i++) { //表格的行
                $("#cale-body").append("<tr row='" + i + "'>");
                for (k = 0; k < 7; k++) { //表格每行的单元格
                    var idx = i * 7 + k; //单元格自然序列号
                    var date_str = idx - firstDay + 2; //计算日期
                    if ((date_str <= 0 || date_str > currMonthDay)) {
                        date_str = "";
                    } //过滤无效日期（小于等于零的、大于月总天数的）
                    $("#cale-body tr[row='" + i + "']").append("<td day='" + date_str + "'><p class='day-num'>" + date_str + "</p></td>");
                }
                $("#cale-body").append("</tr>");
            }
            if (day != null) {
                $("#cale-body tr td[day='" + day + "'] .day-num").css({
                    "border-top-color": "#0072c6",
                    "color": "#0078D7"
                });
            }

            if (isNotNull(selectUser)) {
                $.ajax({
                    url: "getTasks?id=" + userid + "&month=" + (month + 1) + "&year=" + year,
                    type: "get",
                    success: function (result) {
                        for (var i = 0; i < result.length; i++) {
                            var task = result[i];
                            var scheduleStartTime = new Date(task.scheduleStartTime.replace(/-/g, "/"));
                            if (scheduleStartTime < new Date(year, month, 1)) scheduleStartTime = new Date(year, month, 1);//时间小于这月1号，则等于1号
                            var scheduleEndTime = new Date(task.scheduleEndTime.replace(/-/g, "/"));
                            if (scheduleStartTime > new Date(year, month, currMonthDay)) scheduleStartTime = new Date(year, month, currMonthDay);//时间大于月底，则等于月底
                            var timeDiff = scheduleEndTime - scheduleStartTime;
                            timeDiff = Math.floor(timeDiff / (24 * 3600 * 1000)) + 1;//时间差，天数
                            //任务的第一天
                            var taskFirstDay = scheduleStartTime.getDate();
                            for (var j = 0; j < timeDiff; j++) {
                                var temp = $("#cale-body tr td[day='" + (taskFirstDay + j) + "']");
                                var taskcount = temp.data("maxcount");
                                if(taskcount == null){
                                    temp.data("maxcount",1);
                                }else{
                                    temp.data("maxcount",Number(taskcount)+1);
                                }
                            }
                        }
                        var tdCount = $("#cale-body td").length;
                        var maxCount = 0;
                        for(var i=0;i<tdCount;i++){
                            var currCount = $("#cale-body td").eq(i).data("maxcount");
                            if(currCount!=null && currCount>maxCount)
                            maxCount = currCount;
                        }
                        //根据最大一天任务数，设置高度
                        if(maxCount>3){
                            $(".cale-body tr td").css("height",(maxCount-3)*30+130);
                        }
                        for (var i = 0; i < result.length; i++) {
                            var task = result[i];
                            var scheduleStartTime = new Date(task.scheduleStartTime.replace(/-/g, "/"));
                            if (scheduleStartTime < new Date(year, month, 1)) scheduleStartTime = new Date(year, month, 1);//时间小于这月1号，则等于1号
                            var scheduleEndTime = new Date(task.scheduleEndTime.replace(/-/g, "/"));
                            if (scheduleEndTime > new Date(year, month, currMonthDay)) scheduleEndTime = new Date(year, month, currMonthDay);//时间大于月底，则等于月底
                            var isOverTime = (scheduleEndTime - date) < 0 ? true : false;
                            var timeDiff = scheduleEndTime - scheduleStartTime;
                            timeDiff = Math.floor(timeDiff / (24 * 3600 * 1000)) + 1;//时间差，天数
                            var existTaskHeight=0;
//                            for (var j = 0; j <= timeDiff; j++) {
//                                var taskFirstDay = scheduleStartTime.getDate();
//                                var appendP;
//                                if (task.isEnd == 1) {
//                                    appendP = "<p class='task end'>";
//                                } else if (isOverTime) {
//                                    appendP = "<p class='task overtime'>";
//                                } else {
//                                    appendP = "<p class='task onWay'>";
//                                }
//                                appendP = appendP + task.name + "</p>";
//                                $("#cale-body tr td[day='" + (taskFirstDay + j) + "']").append(appendP);
//                            }
                            //任务的第一天
                            var taskFirstDay = scheduleStartTime.getDate();
                            var exsitTaskCount = 0;
                            //计算已存在的任务高度
                            for (var j = 0; j < timeDiff; j++) {
                                var taskcount = $(".calc tbody tr td[day='" + (taskFirstDay + j) + "']").data("taskcount");
                                if(taskcount!=null && taskcount>exsitTaskCount){
                                    exsitTaskCount = taskcount;
                                }
                            }
                            existTaskHeight = exsitTaskCount * 30;
                            var appendP;
                            if (task.isEnd == 1) {
                                appendP = "<p class='task end'>";
                            } else if (isOverTime) {
                                appendP = "<p class='task overtime'>";
                            } else {
                                appendP = "<p class='task onWay'>";
                            }
                            appendP = appendP + task.name + "</p>";
                            //该任务第一天的td
                            var td = $(".calc tbody tr td[day='"+taskFirstDay+"']");
                            var top = td[0].offsetTop;
                            var left = td[0].offsetLeft;
                            //日期的高度加margin
                            var riqiHeight = $(".day-num:contains('20')")[0].offsetHeight+10+existTaskHeight;
                            //td的高宽
                            var tdWidth = $(".calc tbody tr td").eq(0)[0].clientWidth;
                            var tdHeight = $(".calc tbody tr td").eq(0)[0].clientHeight;
                            var trWidth = $(".calc tbody tr").eq(0)[0].clientWidth;
                            //task width
                            var taskWidth = (tdWidth+1) * timeDiff;
                            //第一行宽度
                            var firstWidth = (taskWidth + left)>trWidth?trWidth-left:taskWidth;
                            //总行数
                            var count = Math.ceil((taskWidth - firstWidth)/trWidth)+1;
                            taskWidth = taskWidth - count -3;
                            //element
                            var e;
                            //空隙
                            var kx = 3;
                            //剩余宽度
                            var yuTaskWidth = taskWidth ;
                            //插入任务
                            for(var j=1;j<=count;j++){
                                if(j==1){
                                    e = $(appendP).css({"top":top+riqiHeight,"left":left+kx,"width":firstWidth - (kx*2)});
                                    if(timeDiff==1){
                                        maxCount = $("#cale-body tr td[day='"+taskFirstDay+"']").data("maxcount");
                                        if(maxCount==1){
                                            e.css("height",tdHeight-riqiHeight);
                                        }
                                    }
                                    yuTaskWidth = yuTaskWidth - (firstWidth - (kx*2));
                                }else if(j==count){
                                    e = $(appendP).css({"top":top+riqiHeight+tdHeight*(j-1),"left":0+kx,"width":yuTaskWidth});
                                }else{
                                    e = $(appendP).css({"top":top+riqiHeight+tdHeight*(j-1),"left":0+kx,"width":trWidth - (kx*2)});
                                    yuTaskWidth = yuTaskWidth - (trWidth - (kx*2));
                                }
                                $(".packing").append(e);
                            }
                            //标记存在的任务数
                            for (var j = 0; j < timeDiff; j++) {
                                var temp = $("#cale-body tr td[day='" + (taskFirstDay + j) + "']");
                                var taskcount = temp.data("taskcount");
                                if(taskcount == null){
                                    temp.data("taskcount",1);
                                }else{
                                    temp.data("taskcount",Number(taskcount)+1);
                                }
                            }
                        }
                    }
                });
            }
        });
    }

    function is_leap(year) {
        return (year % 100 == 0 ? res = (year % 400 == 0 ? 1 : 0) : res = (year % 4 == 0 ? 1 : 0));
    }
    
    function deletePage() {
        $(".packing>.task").remove();
        $("#cale-body>*").remove();
        $("#cale-body tr td").removeData("taskcount");
    }
</script>
</body>
</html>

